﻿using System;
using UnityEngine;
using UnityEngine.UI;

namespace BToolkit.ExeUtils
{
    public class EditColor
    {
        InputField input;
        string storageKey;
        string currValue, oldValue;

        public static void Create(InputField input, string key, string defaultValue, Action<Color> onInputChange)
        {
            new EditColor(input, key, defaultValue, onInputChange);
        }

        private EditColor(InputField input, string key, string defaultValue, Action<Color> onInputChange)
        {
            this.input = input;
            this.storageKey = key;
            this.currValue = DataStorage.GetString(storageKey, defaultValue);
            this.input.text = this.currValue;
            this.input.onValueChanged.RemoveAllListeners();
            this.input.onValueChanged.AddListener((string v) =>
            {
                if (onInputChange != null) onInputChange(Color(v));
                this.currValue = v;
            });
            if (onInputChange != null) onInputChange(Color(this.currValue));
            MainController.onEditModeEnable += (bool b, bool save) =>
            {
                if (b)
                {
                    this.currValue = DataStorage.GetString(storageKey, defaultValue);
                    this.input.text = this.currValue;
                    this.oldValue = this.currValue;
                }
                else
                {
                    if (save)
                    {
                        DataStorage.SetString(storageKey, this.currValue);
                    }
                    else
                    {
                        this.input.text = this.oldValue;
                    }
                }
            };
        }

        Color Color(string color)
        {
            Color _color;
            ColorUtility.TryParseHtmlString(color, out _color);
            return _color;
        }
    }
}